<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderSn">
        <el-input
          v-model="queryParams.orderSn"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option label="待支付" value="0" />
          <el-option label="已支付" value="1" />
          <el-option label="已取消" value="2" />
          <el-option label="已退款" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="payType">
        <el-select v-model="queryParams.payType" placeholder="请选择支付方式" clearable>
          <el-option label="微信支付" value="2" />
          <el-option label="支付宝" value="1" />
          <el-option label="其他" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="6">
        <el-card class="statistics-card">
          <div class="statistics-content">
            <div class="statistics-number">{{ statistics.totalCount }}</div>
            <div class="statistics-label">总订单数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card pending">
          <div class="statistics-content">
            <div class="statistics-number">{{ statistics.pendingCount }}</div>
            <div class="statistics-label">待支付</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card success">
          <div class="statistics-content">
            <div class="statistics-number">{{ statistics.paidCount }}</div>
            <div class="statistics-label">已支付</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card cancelled">
          <div class="statistics-content">
            <div class="statistics-number">{{ statistics.cancelledCount }}</div>
            <div class="statistics-label">已取消</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="vipOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderSn" width="" />
      <el-table-column label="用户ID" align="center" prop="userId" width="100" />
      <el-table-column label="VIP天数" align="center" prop="vipDays" width="100" />
      <el-table-column label="订单金额" align="center" prop="amount" width="120">
        <template slot-scope="scope">
          <span>¥{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额" align="center" prop="payAmount" width="120">
        <template slot-scope="scope">
          <span>¥{{ scope.row.payAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="payType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="payTypeOptions" :value="scope.row.payType"/>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="payTime" width="">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCancel(scope.row)"
            v-hasPermi="['vip:order:edit']"
          >取消订单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改VIP订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入订单号" :disabled="form.id != null" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="VIP天数" prop="vipDays">
          <el-input v-model="form.vipDays" placeholder="请输入VIP天数" />
        </el-form-item>
        <el-form-item label="订单金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item label="实付金额" prop="payAmount">
          <el-input v-model="form.payAmount" placeholder="请输入实付金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="payType">
          <el-select v-model="form.payType" placeholder="请选择支付方式">
            <el-option
              v-for="dict in payTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVipOrder, getVipOrder, delVipOrder, addVipOrder, updateVipOrder, completeVipOrder, cancelVipOrder, getVipOrderStatistics } from "@/api/vip/vipOrder";

export default {
  name: "VipOrder",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // VIP订单表格数据
      vipOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderSn: null,
        userId: null,
        status: null,
        payType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderSn: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        vipDays: [
          { required: true, message: "VIP天数不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "订单金额不能为空", trigger: "blur" }
        ],
        payAmount: [
          { required: true, message: "实付金额不能为空", trigger: "blur" }
        ]
      },
      // 支付方式选项
      payTypeOptions: [
        { label: "其他", value: "0" },
        { label: "微信支付", value: "2" },
        { label: "支付宝", value: "1" }
      ],
      // 状态选项
      statusOptions: [
        { label: "待支付", value: "0" },
        { label: "已支付", value: "1" },
        { label: "已取消", value: "2" },
        { label: "已退款", value: "3" }
      ],
      // 统计数据
      statistics: {
        totalCount: 0,
        pendingCount: 0,
        paidCount: 0,
        cancelledCount: 0,
        refundedCount: 0
      }
    };
  },
  created() {
    this.getList();
    this.getStatistics();
  },
  methods: {
    /** 查询VIP订单列表 */
    getList() {
      this.loading = true;
      listVipOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.vipOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取统计数据 */
    getStatistics() {
      getVipOrderStatistics().then(response => {
        this.statistics = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderSn: null,
        userId: null,
        rechargeDataId: null,
        vipDays: null,
        amount: null,
        payAmount: null,
        payType: null,
        status: null,
        payTime: null,
        thirdPartyOrderSn: null,
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加VIP订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVipOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改VIP订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVipOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVipOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除VIP订单编号为"' + ids + '"的数据项？').then(function() {
        return delVipOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('vip/order/export', {
        ...this.queryParams
      }, `vip_order_${new Date().getTime()}.xlsx`)
    },
    /** 更多操作 */
    handleCommand(command, row) {
      switch (command) {
        case "complete":
          this.handleComplete(row);
          break;
        case "cancel":
          this.handleCancel(row);
          break;
        case "detail":
          this.handleDetail(row);
          break;
      }
    },
    /** 完成订单 */
    handleComplete(row) {
      this.$modal.confirm('是否确认完成订单"' + row.orderSn + '"？').then(function() {
        return completeVipOrder(row.orderSn);
      }).then(() => {
        this.getList();
        this.getStatistics();
        this.$modal.msgSuccess("订单完成成功");
      }).catch(() => {});
    },
    /** 取消订单 */
    handleCancel(row) {
      this.$modal.confirm('是否确认取消订单"' + row.orderSn + '"？').then(function() {
        return cancelVipOrder(row.orderSn);
      }).then(() => {
        this.getList();
        this.getStatistics();
        this.$modal.msgSuccess("订单取消成功");
      }).catch(() => {});
    },
    /** 查看详情 */
    handleDetail(row) {
      this.$router.push('/vip/order/detail/' + row.id);
    }
  }
};
</script>

<style lang="scss" scoped>
.statistics-card {
  margin-bottom: 20px;

  .statistics-content {
    text-align: center;

    .statistics-number {
      font-size: 32px;
      font-weight: bold;
      color: #333;
      margin-bottom: 8px;
    }

    .statistics-label {
      font-size: 14px;
      color: #666;
    }
  }

  &.pending .statistics-number {
    color: #e6a23c;
  }

  &.success .statistics-number {
    color: #67c23a;
  }

  &.cancelled .statistics-number {
    color: #f56c6c;
  }
}
</style>
